var api = require('../config/api.js');
// 判断是否请求了用户接口
let memberInfoFlag = false;
/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET") {
    let _timer = null;
    return new Promise(function(resolve, reject) {
        let options = {
            url: url,
            data: data,
            method: method,
            success: async function(res) {
                if (res.statusCode == 200) {
                    resolve(res.data);
                    if(url === api.MemberInfo){
                        memberInfoFlag = true
                    }
                    if(res.data.code == 501){
                        wx.showModal({
                            title: '提示',
                            content: res.data.message,
                            showCancel:false,
                            success (res) {
                              if (res.confirm) {
                                console.log('用户点击确定')
                              }
                            }
                        })
                          
                    }
                }else if(res.statusCode == 401){
                    try{                    
                        wx.clearStorageSync("token");
                        // 请求token
                        await getTokenFromServer();
                        request(url, data, method).then(res=>resolve(res)).catch(err=>reject(res))
                    }catch(err){
                        console.log(err);
                    }
                }else {
                    if(url === api.MemberInfo){
                        memberInfoFlag = true
                    }
                    console.error(res.data.message);
                    reject(res.data);
                }
                wx.hideLoading();

            },
            fail: function(err) {
                reject(err)
                console.log("failed")
                wx.hideLoading();
                // wx.showToast({
                //     title: '请求超时,请检查网络',
                //     icon: 'none',
                //     duration: 3000
                // })
            }
        }
        if(url === api.AuthLoginByWeixin || url === api.MemberVerify){
            // 获取token
            options.header = getHeader();
            wx.request(options)
        }else if(url === api.MemberInfo){
            options.header = getHeader();
            wx.request(options)
        }else{
            _timer = setInterval(function(){
                if(hasToken() && memberInfoFlag){
                    clearInterval(_timer);
                    options.header = getHeader();
                    wx.request(options)
                }
            },500);
        }
    });
}

function wxLogin(user) {
    let code = null;
    return new Promise(function (resolve, reject) {
        return login().then((res) => {
            code = res.code;
        return user

    }).then((user) => {

            //登录远程服务器
            let pram = {
                ...user
            }
            request(api.memberUpdate, pram, 'POST').then(res => {
                if (res.code == 200) {
                    //存储用户信息
                    request(api.MemberInfo).then(result=>{
                        if(result.code==200){
                            resolve(result);
                        }
                    }).catch((erro)=>{
                        console.log(erro)
                        reject(erro);
                    })

                }
            }).catch((err) => {
                    reject(err);
            });
        }).catch((err) => {
                reject(err);
        })
    });
}
/**
 * 检查微信会话是否过期
 */
function checkSession() {
    return new Promise(function(resolve, reject) {
        wx.checkSession({
            success: function() {
                resolve(true);
            },
            fail: function() {
                reject(false);
            }
        })
    });
}

/**
 * 调用微信登录
 */
function login() {
    return new Promise(function(resolve, reject) {
        wx.login({
            success: function(res) {
                if (res.code) {
                    //登录远程服务器
                    resolve(res);

                } else {
                    reject(res);
                }
            },
            fail: function(err) {
                reject(err);
            }
        });
    });
}
function refreshThisPage() {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route //当前页面url
    wx.reLaunch({
        url: `/${url}`
    });
}
function getUserInfo() {
    return new Promise(function(resolve, reject) {
        wx.getUserInfo({
            withCredentials: true,
            success: function(res) {
                console.log(res)
                resolve(res);
            },
            fail: function(err) {
                reject(err);
            }
        })
    });
}

function redirect(url) {

    //判断页面是否需要登录
    if (false) {
        wx.redirectTo({
            url: '/pages/auth/login/login'
        });
        return false;
    } else {
        wx.redirectTo({
            url: url
        });
    }
}

function hasToken(){
    const token = wx.getStorageSync("token");
    return token ? true : false;     
}

function getHeader(){
    const header = {
        'Content-Type': 'application/json',
        'X-Access-Token': wx.getStorageSync('token')
    }
    return header;
}

function getTokenFromServer(){
    //等待微信登录
    console.log("2223434");
    let _this = this;
    return new Promise((resolve, reject)=>{
        wx.login({
            success: res => {
                let pram = {
                    code: res.code,
                    maType: 1
                }
                request(api.AuthLoginByWeixin, pram, 'POST').then(res => {
                    if (res.code == 200) {
                        //存储用户信息
                        wx.setStorageSync('token', res.result.token);
                        resolve(res);
                    }
                }).catch((err) => {
                    console.log(err);
                    reject(err);
                });
            }
        })
    });
    
}

function showErrorToast(msg) {
    wx.showToast({
        title: msg,
        image: '/static/images/icon_error.png'
    })
}

/**
 * wxPromisify
 * @fn 传入的函数，如wx.request、wx.download
 */

function wxPromisify(fn) {
    return function (obj = {}) {
        return new Promise((resolve, reject) => {
            obj.success = function (res) {
            resolve(res)
        }

        obj.fail = function (res) {
            reject(res)
        }

        fn(obj)//执行函数，obj为传入函数的参数
    })
    }
}

function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}
function formatTime(number,format) {

    var formateArr  = ['Y','M','D','h','m','s'];
    var returnArr   = [];

    var date = new Date(number * 1000);
    returnArr.push(date.getFullYear());
    returnArr.push(formatNumber(date.getMonth() + 1));
    returnArr.push(formatNumber(date.getDate()));

    returnArr.push(formatNumber(date.getHours()));
    returnArr.push(formatNumber(date.getMinutes()));
    returnArr.push(formatNumber(date.getSeconds()));
    for (var i in returnArr)
    {
        format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;
}
//取倒计时（天时分秒）
function getTimeLeft(datetimeTo){
    // 计算目标与现在时间差（毫秒）
    let time1 = new Date(datetimeTo).getTime();
    let time2 = new Date().getTime();
    let mss = time1 - time2;
    if(mss <=0){
        return 0
    }
    // 将时间差（毫秒）格式为：天时分秒
    let days = parseInt(mss / (1000 * 60 * 60 * 24));
    let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = parseInt((mss % (1000 * 60)) / 1000);

    return {
        days:days,
        hours:hours,
        minutes:minutes,
        seconds:seconds
    }
  }

  function rad(d) {
    return d * Math.PI / 180.0;
}
// 以今天为基准，如果要获取昨天的日期，num就是-1， 前天的就是-2，依次类推。str表示年月日间的分割方式
function getDay(num, str) {
    var today = new Date();
    var nowTime = today.getTime();
    var ms = 24*3600*1000*num;
    today.setTime(parseInt(nowTime + ms));
    var oYear = today.getFullYear();
    var oMoth = (today.getMonth() + 1).toString();
    if (oMoth.length <= 1) oMoth = '0' + oMoth;
    var oDay = today.getDate().toString();
    if (oDay.length <= 1) oDay = '0' + oDay;
    return oYear + str + oMoth + str + oDay;
}

// 根据经纬度计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
function getDistance(lat1, lng1, lat2, lng2) {

    var radLat1 = rad(lat1);
    var radLat2 = rad(lat2);
    var a = radLat1 - radLat2;
    var b = rad(lng1) - rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137; // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000; //输出为公里

    var distance = s;
    var distance_str = "";

    if (parseInt(distance) >= 1) {
        distance_str = distance.toFixed(1) + "km";
    } else {
        distance_str = distance * 1000 + "m";
    }

    //s=s.toFixed(4);

    console.info('lyj 距离是', s);
    console.info('lyj 距离是', distance_str);
    return s;
}

function getQueryString(path, name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = path.split("?")[1].match(reg);
    if (r != null) {
        return decodeURIComponent(r[2]);
    };
    return null;
}

module.exports = {
    getDistance,
    formatTime,
    request,
    redirect,
    showErrorToast,
    checkSession,
    login,
    wxLogin,
    getUserInfo,
    wxPromisify,
    getTimeLeft,
    getTokenFromServer,
    getDay,
    getQueryString
}

